<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>猜数字游戏</title>
</head>
<body>
    <button id="resetBtn">重来一局</button><br>
    <span>要猜的数字: </span><br>
    <input type="text" value="0">
    <button id="guess">猜</button><br>
    <span>结果: </span><span id="result"></span><br>
    <span>已经猜的次数:</span><span id="count">0</span>

    <script>
        // 拿到上述元素
        let resetBtn = document.querySelector('#resetBtn');
        let input = document.querySelector('input');
        let guess = document.querySelector('#guess');
        let result = document.querySelector('#result');
        let count = document.querySelector('#count');

        // 生成随机数[1,100] floor:向下取整
        let toGuess = Math.floor(Math.random()*100+1);
        console.log(toGuess);

        // 实现点击猜按钮,猜数字
        guess.onclick = function(){
            if(input.value == ''){
                return ;
            }
            let num = parseInt(input.value);
            if(num < toGuess){
                result.innerHTML = '数字太小啦';
                result.style.color = 'red';
            }else if(num > toGuess){
                result.innerHTML = '数字太大啦';
                result.style.color = 'red';
            }else {
                result.innerHTML = '恭喜你猜对了';
                result.style.color = 'green';
            }
            // 更新猜的次数
            let guessNumber = parseInt(count.innerHTML);
            guessNumber++;
            count.innerHTML = guessNumber;
        }

        // 再来一局
        resetBtn.onclick = function(){
            // 刷新页面
            location.reload();
        }
    </script>
</body>
</html>